<script setup lang="ts">
import { getCodeImg } from '@/api/login';
import { getConfigKey } from '@/api/system/config';
import { decrypt, encrypt } from '@/utils/jsencrypt';
import { useUserStore } from '@/store/modules/user';
import { getLoginStyle } from '@/utils/widthUtils';

const userStore = useUserStore();
const router = useRouter();
const { proxy } = getCurrentInstance() as ComponentInternalInstance;

const loginFormRef = ref<ElFormInstance>();

const loginForm = ref({
  username: 'admin',
  password: 'admin123',
  rememberMe: false,
  code: '',
  uuid: ''
});
const loginRules = {
  username: [{ required: true, trigger: 'blur', message: '请输入您的账号' }],
  password: [{ required: true, trigger: 'blur', message: '请输入您的密码' }],
  code: [{ required: true, trigger: 'change', message: '请输入验证码' }]
};

const codeUrl = ref('');
const loading = ref(false);
// 验证码开关
const captchaEnabled = ref(false);
// 注册开关
const register = ref(false);
const redirect = ref(undefined);
getConfigKey('sys.account.captchaEnabled').then(res => captchaEnabled.value = res.msg === 'true');
getConfigKey('sys.account.registerUser').then(res => register.value = res.msg === 'true');

const handleLogin = () => {
  loginFormRef.value.validate(async (valid: boolean) => {
    if (valid) {
      loading.value = true;
      // 勾选了需要记住密码设置在 cookie 中设置记住用户名和密码
      if (loginForm.value.rememberMe) {
        localStorage.setItem('username', loginForm.value.username);
        localStorage.setItem('password', encrypt(loginForm.value.password));
        localStorage.setItem('rememberMe', loginForm.value.rememberMe as any);
      } else {
        // 否则移除
        localStorage.removeItem('username');
        localStorage.removeItem('password');
        localStorage.removeItem('rememberMe');
      }
      // 调用action的登录方法
      userStore.login(loginForm.value).then(() => {
        router.push({ path: redirect.value || '/' });
      }).catch(() => {
        loading.value = false;
        // 重新获取验证码
        if (captchaEnabled.value) {
          getCode();
        }
      });
    }
  });
};

const getCode = () => {
  getCodeImg().then(res => {
    captchaEnabled.value = res.captchaEnabled === undefined ? true : res.captchaEnabled;
    if (captchaEnabled.value) {
      codeUrl.value = 'data:image/gif;base64,' + res.img;
      loginForm.value.uuid = res.uuid;
    }
  });
};

const getCookie = () => {
  const username = localStorage.getItem('username');
  const password = localStorage.getItem('password');
  const rememberMe = localStorage.getItem('rememberMe');
  loginForm.value = {
    username: !username ? loginForm.value.username : username,
    password: !password ? loginForm.value.password : decrypt(password),
    rememberMe: !rememberMe ? false : Boolean(rememberMe)
  } as any;
};

const loginStyle = ref({
  fromWidth: {
    width: '60%'
  },
  titleShow: true,
  formStyle: {
    left: '60%',
    top: '52%',
    width: 'auto'
  },
  containerSize: {
    width: '60%',
    height: '60%'
  },
  containerStyle: {
    borderRadius: '10px'
  }
});

onMounted(() => {
  loginStyle.value = getLoginStyle();
  getCode();
  getCookie();
});

</script>

<template>
  <div class="login">
    <div class="container" :style="loginStyle.containerSize">
      <div class="container-style" :style="loginStyle.containerStyle">
        <div class="title-box" v-show="loginStyle.titleShow">
          <div class="title-container">
            <div class="title-style">
              <div class="logo">
                后台管理系统
              </div>
            </div>
          </div>
        </div>
        <div class="form-box" :style="loginStyle.fromWidth">
          <div class="form-container">
            <div class="logo" v-show="!loginStyle.titleShow">
              后台管理系统
            </div>
            <el-form ref="loginFormRef" :model="loginForm" :rules="loginRules" class="form-style"
                     :style="loginStyle.formStyle">
              <el-form-item prop="username">
                <el-input v-model="loginForm.username" type="text" size="large" auto-complete="off"
                          placeholder="账号">
                  <template #prefix>
                    <svg-icon icon-class="user" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="password">
                <el-input v-model="loginForm.password" type="password" size="large" auto-complete="off" show-password
                          placeholder="密码"
                          @keyup.enter="handleLogin">
                  <template #prefix>
                    <svg-icon icon-class="password" />
                  </template>
                </el-input>
              </el-form-item>
              <el-form-item prop="code" v-if="captchaEnabled">
                <el-space>
                  <el-input v-model="loginForm.code" size="large" auto-complete="off" placeholder="验证码"
                            style="width: 50%"
                            @keyup.enter="handleLogin">
                    <template #prefix>
                      <svg-icon icon-class="validCode" />
                    </template>
                  </el-input>
                  <div style="display: flex">
                    <img :src="codeUrl" @click="getCode" class="code-img" />
                  </div>
                </el-space>
              </el-form-item>
              <el-checkbox v-model="loginForm.rememberMe" style="margin:0px 0px 5px 0px;">记住密码</el-checkbox>
              <el-form-item style="width:100%;">
                <el-button :loading="loading" size="large" type="primary" style="width:100%;"
                           @click.prevent="handleLogin">
                  <span v-if="!loading">登 录</span>
                  <span v-else>登 录 中...</span>
                </el-button>
                <div style="float: right;" v-if="register">
                  <router-link class="link-type" :to="'/register'">立即注册</router-link>
                </div>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </div>
    </div>
    <!--  底部  -->
    <div class="el-login-footer">
      <span></span>
    </div>
  </div>
</template>

<style lang='scss' scoped>
.login {
  height: 100%;
  width: 100%;
  background-image: url('@/assets/images/login-background.jpg');
  background-size: cover;
}

.container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.container-style {
  width: 100%;
  height: 100%;
  border: none;
  background-color: #fff;
  display: flex;
  //background-color: rgba(255, 255, 255, 0.2); /* 半透明背景 */
  //backdrop-filter: blur(10px); /* 创建毛玻璃效果 */
}

.logo {
  padding-top: 1em;
  font-family: 宋体;
  font-size: 2em;
  font-weight: bolder;
  text-align: center;
  color: #531dab;
}

.form-box {
  height: 100%;
  border-radius: 25px
}

.form-container {
  position: relative;
  width: 100%;
  height: 100%;
}

.form-style {
  position: absolute;
  transform: translate(-50%, -50%);
}

.title-box {
  height: 100%;
  flex-grow: 1;
  border-radius: 25px;
  position: relative
}

.title-container {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

.title-style {
  width: 600px;
  height: 500px;
  border-radius: 25px;
  background: #9cc8f7;
  box-shadow: 3px 3px 12px #85aad2,
  -3px -3px 12px #b3e6ff;
}

.login-form-forgot {
  float: right;
}

.login-form-button {
  width: 100%;
}

.code-img {
  margin: auto;
  width: 100px;
  height: 39px;
  border-radius: 5px;
}
</style>
